<template>
  <div id="uploadPictureToMySpacePage">
    <h2 style="margin-bottom: 16px; text-align: center">
      {{ picture && uploadType === 'file' ? `点击图片可重新上传` : `上传新图片` }}
    </h2>
    <a-typography-paragraph v-if="spaceId" type="secondary" style="text-align: center">
      保存至{{ spaceType === 0 ? '个人云' : '团队云' }}：<a
        :href="`/space/${spaceId}`"
        target="_blank"
      >
        {{ spaceName ?? spaceId }}</a
      >
    </a-typography-paragraph>
    <!-- 选择图片上传方式 -->
    <a-tabs v-model:activeKey="uploadType">
      <a-tab-pane key="file" tab="文件上传">
        <!-- 图片文件上传 -->
        <PictureUpload :picture="picture" :spaceId="spaceId" :on-success="onSuccess" />
      </a-tab-pane>
      <a-tab-pane key="url" tab="网址上传" force-render>
        <!-- 图片地址上传 -->
        <UrlPictureUpload :picture="picture" :spaceId="spaceId" :on-success="onSuccess" />
      </a-tab-pane>
    </a-tabs>
    <!-- 图片信息表单 -->
    <a-form
      v-if="picture && uploadType !== 'batch'"
      layout="vertical"
      :model="pictureForm"
      @finish="handleSubmit"
    >
      <a-form-item label="图片名称" name="name">
        <a-input
          v-model:value="pictureForm.name"
          style="max-width: 320px"
          placeholder="请输入图片名"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="图片简介" name="introduction">
        <a-textarea
          v-model:value="pictureForm.introduction"
          placeholder="介绍一下这个图片吧"
          :autoSize="{ minRows: 1, maxRows: 5 }"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="图片分类" name="category">
        <a-auto-complete
          v-model:value="pictureForm.category"
          placeholder="可自定义图片分类"
          :options="categoryOptions"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="图片标签" name="tags">
        <a-select
          v-model:value="pictureForm.tags"
          mode="tags"
          placeholder="可自定义图片标签"
          :options="tagOptions"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-flex>
          <a-button
            type="text"
            danger
            @click="cancelUploadClearData"
            block
            :icon="h(CloseOutlined)"
          >
            取消创建
          </a-button>
          <a-button type="text" html-type="submit" block :icon="h(CloudUploadOutlined)">
            保存至{{ spaceType === 0 ? '个人云' : '团队云' }}
          </a-button>
        </a-flex>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import PictureUpload from '@/components/PictureUpload.vue'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import { computed, h, onMounted, reactive, ref, watch } from 'vue'
import {
  deletePictureUsingPost,
  editPictureUsingPost,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import { CloseOutlined, CloudUploadOutlined } from '@ant-design/icons-vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'

const picture = ref<API.PictureVO>()
// 图片信息表单，类型是编辑图片请求体，默认是空对象
const pictureForm = reactive<API.PictureEditRequest>({})

// 上传方式（默认文件上传）
const uploadType = ref<'file' | 'url' | 'batch'>('file')

const router = useRouter()
const route = useRoute()

// 如果要上传图到个人云，获取空间Id，并用计算属性包裹
const spaceId = computed(() => {
  return route.query?.spaceId
})

const spaceName = ref<string>()
const spaceType = ref<number>()

const getSpaceNameAndType = async () => {
  const res = await getSpaceVoByIdUsingGet({
    // @ts-ignore
    id: spaceId.value,
  })
  if (res.data.code === 0 && res.data.data) {
    spaceName.value = res.data.data?.spaceName
    spaceType.value = res.data.data?.spaceType
  } else {
    message.error('获取云名称失败，' + res.data.message)
  }
}
/**
 * 图片上传成功，回显图片和图片名称
 * @param newPicture
 */
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}

/**
 * 提交表单上传图片
 * @param values
 */
const handleSubmit = async (values: any) => {
  const pictureId = picture.value?.id
  if (!pictureId) {
    return
  }
  const res = await editPictureUsingPost({
    id: pictureId,
    spaceId: spaceId.value,
    ...values,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('创建成功')
    // 跳转到图片详情页
    router.push({
      path: `/picture/${pictureId}`,
    })
  } else {
    message.error('创建失败，' + res.data.message)
  }
}

/**
 * 取消创建图片（同时删除图片对象存储和数据库的数据）
 */
const cancelUploadClearData = async () => {
  // 前端校验一下id是否有效
  // 注意删除图片的时候用id，因为deleteRequest请求体接收的是id，而不是pictureId
  const id = picture.value?.id
  if (!id) {
    message.error('无需删除，该图片已不存在')
    // 取消创建图片后，跳转到主页
    router.push('/')
    return
  }
  // @ts-ignore
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('取消创建图片成功')
    // 取消创建图片后，跳转到主页
    router.push('/')
  } else {
    message.error('取消创建图片失败，' + res.data.message)
  }
}

// 监听图片名长度，超过18个字符给出警告
watch(
  () => pictureForm.name,
  (newName) => {
    if (newName && newName.length > 18) {
      message.warn('图片名至多 18 个字符，请适当缩短')
    }
  },
)
// 监听图片简介长度，超过80个字符给出警告
watch(
  () => pictureForm.introduction,
  (newIntroduction) => {
    if (newIntroduction && newIntroduction.length > 80) {
      message.warn('图片简介至多 80 个字符，请适当缩短')
    }
  },
)
// 监听图片标签数量，超过6个标签给出警告
watch(
  () => pictureForm.tags,
  (newTags) => {
    if (newTags && newTags.length > 6) {
      message.warn('标签数量至多 6 个，请适当减少')
    }
  },
  { deep: true },
)

const categoryOptions = ref<String[]>([])
const tagOptions = ref<String[]>()

/**
 * 进入创建图片页面 展示默认标签和分类选项
 */
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // @ts-ignore
    tagOptions.value = (res.data.data.tagList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
    // @ts-ignore
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('默认分类标签列表展示失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
  getSpaceNameAndType()
})
</script>

<style scoped>
#uploadPictureToMySpacePage {
  max-width: 550px;
  margin: 0 auto;
}
</style>
